'use client';

import React, { useState, useEffect } from 'react';
import { Table, Tag, Card, Button, Modal, Form, Input, InputNumber, message, Alert } from 'antd';
import { request } from '@/utils/request';
import Swal from 'sweetalert2';
import { PlusOutlined } from '@ant-design/icons';

interface UserInfo {
  id: number;
  nickname: string;
  phone: string;
  email?: string;
  avatar?: string;
  points: number;
  withDrawPoints: number; // 可提现积分
}

interface WithdrawablePointsResponse {
  id: number;
  nickname: string;
  phone: string;
  email?: string;
  avatar?: string;
  totalPoints: number;
  frozenPoints: number;
  withdrawablePoints: number;
}

interface WithdrawRecord {
  id: number;
  withdrawNo: string;
  amount: number;
  actualAmount: number;
  accountType: string;
  accountInfo: any;
  status: string;
  createdAt: string;
  processedAt?: string;
  completedAt?: string;
}

interface WithdrawForm {
  amount: number;
  alipayAccount: string;
  realName: string;
}

const WithdrawPage = () => {
  const [userInfo, setUserInfo] = useState<UserInfo | null>(null);
  const [records, setRecords] = useState<WithdrawRecord[]>([]);
  const [loading, setLoading] = useState(false);
  const [withdrawModalVisible, setWithdrawModalVisible] = useState(false);
  const [withdrawLoading, setWithdrawLoading] = useState(false);
  const [form] = Form.useForm();
  const [inputAmount, setInputAmount] = useState(100);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });
  const [queryLoadingMap, setQueryLoadingMap] = useState<{[key: string]: boolean}>({});
  const [queryStatusMap, setQueryStatusMap] = useState<{[key: string]: string}>({});

  // 获取用户信息
  useEffect(() => {
    const fetchUserInfo = async () => {
      try {
        const response = await request('/user/withdrawable-points', {
          method: 'GET'
        });

        if (response.code === 0 && response.data) {
          const userData = response.data as WithdrawablePointsResponse;
          setUserInfo({
            id: userData.id,
            nickname: userData.nickname,
            phone: userData.phone,
            email: userData.email,
            avatar: userData.avatar,
            points: userData.totalPoints,
            withDrawPoints: userData.withdrawablePoints
          });
        }
      } catch (error) {
        console.error('获取用户信息失败:', error);
      }
    };

    fetchUserInfo();
  }, []);

  // 获取提现记录
  const fetchRecords = async (page = 1, pageSize = 10) => {
    try {
      setLoading(true);
      const response = await request(`/user/withdraw-records?page=${page}&pageSize=${pageSize}`, {
        method: 'GET'
      });

      if (response.code === 0 && response.data) {
        const data = response.data as any;
        setRecords(data.records || []);
        setPagination({
          current: page,
          pageSize,
          total: data.total || 0
        });
      }
    } catch (error) {
      console.error('获取提现记录失败:', error);
      message.error('获取提现记录失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchRecords();
  }, []);

  // 处理分页变化
  const handleTableChange = (pagination: any) => {
    fetchRecords(pagination.current, pagination.pageSize);
  };

  // 查询转账状态
  const handleCheckTransferStatus = async (withdrawNo: string) => {
    try {
      // 设置该按钮的loading状态
      setQueryLoadingMap(prev => ({ ...prev, [withdrawNo]: true }));
      
      const response = await fetch('/api/payment/alipay/query-transfer', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ outBizNo: withdrawNo })
      });

      const result = await response.json();
      if (result.code === 0) {
        const transferInfo = result.data;
        
        // 记录查询状态
        let statusText = '';
        if (transferInfo.status === 'SUCCESS') {
          statusText = '转账成功';
          message.success('转账成功！');
        } else if (transferInfo.status === 'FAILED') {
          statusText = `转账失败: ${transferInfo.failReason || '未知原因'}`;
          message.error(statusText);
        } else {
          statusText = `转账状态: ${transferInfo.status}`;
          message.info(statusText);
        }
        
        setQueryStatusMap(prev => ({ ...prev, [withdrawNo]: statusText }));
        
        // 刷新提现记录
        fetchRecords();
      } else {
        const errorText = result.message || '查询失败';
        setQueryStatusMap(prev => ({ ...prev, [withdrawNo]: errorText }));
        message.error(errorText);
      }
    } catch (error) {
      console.error('查询转账状态失败:', error);
      const errorText = '查询转账状态失败';
      setQueryStatusMap(prev => ({ ...prev, [withdrawNo]: errorText }));
      message.error(errorText);
    } finally {
      // 清除该按钮的loading状态
      setQueryLoadingMap(prev => ({ ...prev, [withdrawNo]: false }));
    }
  };

  // 处理提现提交
  const handleWithdraw = async (values: WithdrawForm) => {
    if (!userInfo) {
      message.error('用户信息获取失败');
      return;
    }

    if (values.amount > userInfo.withDrawPoints) {
      message.error('提现金额不能超过可提现积分');
      return;
    }

    try {
      setWithdrawLoading(true);

      // 调用提现API
      const response = await request('/payment/alipay/withdraw', {
        method: 'POST',
        body: JSON.stringify({
          taskId: 0, // 这里需要根据实际情况传入任务ID
          amount: values.amount,
          accountType: 'alipay',
          accountInfo: {
            account: values.alipayAccount,
            realName: values.realName
          }
        })
      });

      if (response.code === 0) {
        Swal.fire({
          title: '提现申请提交成功！',
          text: '您的提现申请已提交，我们将在1-3个工作日内处理完成。',
          icon: 'success',
          confirmButtonText: '确定'
        });
        
        // 刷新用户信息和提现记录
        const userResponse = await request('/user/withdrawable-points', {
          method: 'GET'
        });
        if (userResponse.code === 0 && userResponse.data) {
          const userData = userResponse.data as WithdrawablePointsResponse;
          setUserInfo({
            id: userData.id,
            nickname: userData.nickname,
            phone: userData.phone,
            email: userData.email,
            avatar: userData.avatar,
            points: userData.totalPoints,
            withDrawPoints: userData.withdrawablePoints
          });
        }
        
        fetchRecords(); // 刷新提现记录
        form.resetFields();
        setWithdrawModalVisible(false);
      } else {
        message.error(response.message || '提现申请提交失败');
      }
    } catch (error) {
      console.error('提现失败:', error);
      message.error('提现申请提交失败，请稍后重试');
    } finally {
      setWithdrawLoading(false);
    }
  };

  // 状态配置
  const statusConfig = {
    PENDING: { text: '待处理', color: 'processing' },
    PROCESSING: { text: '处理中', color: 'processing' },
    SUCCESS: { text: '成功', color: 'success' },
    FAILED: { text: '失败', color: 'error' },
    CANCELLED: { text: '已取消', color: 'default' }
  };

  // 表格列定义
  const columns = [
    {
      title: '提现单号',
      dataIndex: 'withdrawNo',
      key: 'withdrawNo',
      width: 200,
      render: (withdrawNo: string) => (
        <span className="font-mono text-sm">{withdrawNo}</span>
      )
    },
    {
      title: '提现金额',
      dataIndex: 'amount',
      key: 'amount',
      width: 120,
      render: (amount: number) => (
        <span className="font-medium text-cyan-600">¥{(amount).toFixed(2)}</span>
      )
    },
    {
      title: '实际到账',
      dataIndex: 'actualAmount',
      key: 'actualAmount',
      width: 120,
      render: (actualAmount: number) => (
        <span className="font-medium text-green-600">¥{(actualAmount).toFixed(2)}</span>
      )
    },
    {
      title: '支付宝账号',
      dataIndex: 'accountInfo',
      key: 'accountInfo',
      width: 150,
      render: (accountInfo: any) => {
        try {
          const info = typeof accountInfo === 'string' ? JSON.parse(accountInfo) : accountInfo;
          return info?.account || '-';
        } catch {
          return '-';
        }
      }
    },
    {
      title: '真实姓名',
      dataIndex: 'accountInfo',
      key: 'realName',
      width: 120,
      render: (accountInfo: any) => {
        try {
          const info = typeof accountInfo === 'string' ? JSON.parse(accountInfo) : accountInfo;
          return info?.realName || '-';
        } catch {
          return '-';
        }
      }
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: string) => {
        const config = statusConfig[status as keyof typeof statusConfig] || { text: status, color: 'default' };
        return <Tag color={config.color}>{config.text}</Tag>;
      }
    },
    {
      title: '申请时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 180,
      render: (createdAt: string) => {
        const date = new Date(createdAt);
        return date.toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit'
        });
      }
    },
    {
      title: '完成时间',
      dataIndex: 'completedAt',
      key: 'completedAt',
      width: 180,
      render: (completedAt: string) => {
        if (!completedAt) return '-';
        const date = new Date(completedAt);
        return date.toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit'
        });
      }
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      render: (_: any, record: WithdrawRecord) => (
        <Button 
          size="small" 
          onClick={() => handleCheckTransferStatus(record.withdrawNo)}
          disabled={record.status === 'SUCCESS' || record.status === 'FAILED'}
          loading={queryLoadingMap[record.withdrawNo]}
        >
          {queryLoadingMap[record.withdrawNo] ? '查询中...' : 
           queryStatusMap[record.withdrawNo] ? queryStatusMap[record.withdrawNo] : 
           record.status === 'PROCESSING' ? '查询提现状态' : '查询状态'}
        </Button>
      )
    }
  ];

  return (
    <div>
      {/* 页面标题和提现按钮 */}
      <div className="flex justify-between items-center mb-6">
        <div>
          <h2 className="text-2xl font-bold text-gray-800 mb-2">提现人民币</h2>
          <p className="text-gray-600">管理您的人民币提现申请</p>
        </div>
        <div className="text-right">
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => setWithdrawModalVisible(true)}
            disabled={!userInfo?.withDrawPoints || userInfo.withDrawPoints < 100}
            className="h-10 px-6"
          >
            申请提现
          </Button>
          <div className="text-xs text-gray-500 mt-2">
            至少需要100积分才可以提现
          </div>
        </div>
      </div>

      {/* 用户积分信息 */}
      <Card className="mb-6">
        <div className="flex justify-between items-center">
          <div className="text-center flex-1">
            <div className="text-3xl font-bold text-cyan-600 mb-2">
              {userInfo?.withDrawPoints || 0}
            </div>
            <div className="text-gray-600">可提现积分</div>
          </div>
          <div className="text-right">
            <Button
              type="default"
              size="small"
              onClick={() => fetchRecords(1, 2)}
              loading={loading}
            >
              查询最近记录
            </Button>
          </div>
        </div>
      </Card>

      {/* 提现记录表格 */}
      <Card>
        <Table
          columns={columns}
          dataSource={records}
          rowKey="id"
          loading={loading}
          pagination={{
            current: pagination.current,
            pageSize: pagination.pageSize,
            total: pagination.total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条记录`
          }}
          onChange={handleTableChange}
          scroll={{ x: 1200 }}
        />
      </Card>

      {/* 提现申请弹窗 */}
      <Modal
        title="申请人民币提现"
        open={withdrawModalVisible}
        onCancel={() => {
          setWithdrawModalVisible(false);
          form.resetFields();
        }}
        footer={null}
        width={500}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleWithdraw}
          initialValues={{
            amount: 100
          }}
        >
          <Form.Item
            label="提现金额（积分）"
            name="amount"
            rules={[
              { required: true, message: '请输入提现金额' },
              { 
                type: 'number', 
                min: 100, 
                message: '最低提现100积分',
                transform: (value) => Number(value)
              },
              {
                validator: (_, value) => {
                  if (!value || value < 100) {
                    return Promise.reject('最低提现100积分');
                  }
                  if (userInfo && value > userInfo.withDrawPoints) {
                    return Promise.reject('提现金额不能超过可提现积分');
                  }
                  return Promise.resolve();
                }
              }
            ]}
          >
            <div className="flex items-center gap-4">
              <InputNumber
                className="flex-1"
                min={100}
                max={userInfo?.withDrawPoints || 100}
                precision={0}
                placeholder="请输入提现金额"
                onChange={(value) => {
                  setInputAmount(value || 100);
                  form.setFieldValue('amount', value || 100);
                }}
              />
              <div className="text-sm text-gray-600">
                <div>可提现：{userInfo?.withDrawPoints || 0} 积分</div>
                <div className="text-cyan-600 font-medium">
                  剩余：{(userInfo?.withDrawPoints || 0) - inputAmount} 积分
                </div>
              </div>
            </div>
          </Form.Item>

          <Form.Item
            label="支付宝账号"
            name="alipayAccount"
            rules={[
              { required: true, message: '请输入支付宝账号' },
            ]}
          >
            <Input placeholder="请输入支付宝绑定的手机号" />
          </Form.Item>

          <Form.Item
            label="真实姓名"
            name="realName"
            rules={[
              { required: true, message: '请输入真实姓名' },
              { min: 2, max: 20, message: '姓名长度在2-20个字符之间' }
            ]}
          >
            <Input placeholder="请输入您的真实姓名" />
          </Form.Item>

          {/* 费用计算显示 */}
          <div className="mb-6 p-4 bg-gray-50 rounded-lg">
            <div className="flex justify-between items-center mb-2">
              <span className="text-gray-600">提现金额：</span>
              <span className="font-medium">{inputAmount} 积分</span>
            </div>
            <div className="flex justify-between items-center pt-2 border-t border-gray-200">
              <span className="text-gray-800 font-medium">实际到账：</span>
              <span className="text-cyan-600 font-bold text-lg">
                ¥{(inputAmount / 10).toFixed(2)}
              </span>
            </div>
          </div>

          <Form.Item>
            <div className="flex justify-end space-x-3">
              <Button onClick={() => {
                setWithdrawModalVisible(false);
                form.resetFields();
              }}>
                取消
              </Button>
              <Button
                type="primary"
                htmlType="submit"
                loading={withdrawLoading}
                disabled={!userInfo?.withDrawPoints || userInfo.withDrawPoints < 100}
              >
                {withdrawLoading ? '提交中...' : '确认提现'}
              </Button>
            </div>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default WithdrawPage; 